package com.example.utils;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * 公共字段填充类
 * 针对pojo中字段有指定@TableField(fill = FieldFill....)注解
 * 在插入或更新数据时候，会自动调用此类中的方法，进行字段填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createTime")) {
            metaObject.setValue("createTime", new Timestamp(System.currentTimeMillis()));
        }

        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", new Timestamp(System.currentTimeMillis()));
        }

        if (UserHolder.getUser() != null) {
            if (metaObject.hasSetter("createPerson")) {
                metaObject.setValue("createPerson", UserHolder.getUser().getId());
            }

            if (metaObject.hasSetter("updatePerson")) {
                metaObject.setValue("updatePerson", UserHolder.getUser().getId());
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (UserHolder.getUser() != null) {
            if (metaObject.hasSetter("updatePerson")) {
                metaObject.setValue("updatePerson", UserHolder.getUser().getId());
            }
        }

        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", new Timestamp(System.currentTimeMillis()));
        }
    }
}
